package com.dragon.common.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.common.utils.ServerProperties;

@Component
public class PropertiesLoadUtil {
	//缓存不同properties文件内容
	private static Map<String,Properties> cacheProperties = new ConcurrentHashMap<String,Properties>();
	
	//配置文件缓存时效控制
	private static Map<String,Long> preLoadTime = new ConcurrentHashMap<String,Long>();
	//动态加载间隔时长  5分钟
	private static final int DYNAMIC_LOAD_TIME = 300000;
	
	private static String configPropertiesPath;
	
	public String getConfigPropertiesPath() {
		return configPropertiesPath;
	}
	
	@Value("${config.properties.path}")
	public void setConfigPropertiesPath(String configPropertiesPath) {
		PropertiesLoadUtil.configPropertiesPath = configPropertiesPath;
	}
	
	/**
	 * 获取指定propertis 文件的Properties对象
	 * @param fileName
	 * @return
	 */
	public static Properties getProperties(String resourceName){
		return loadProperties(resourceName);
	}
	
	/**
	 * 获取指定文件 的指定属性值
	 * @param key
	 * @param fileName
	 * @return
	 */
	public static String getPropertiesValue(String key,String resourceName){
		return StringUtils.trim(ServerProperties.getValue(configPropertiesPath, resourceName, key));
		//return StringUtils.trim(getDynamicProperty(key,resourceName));
	}
	
	//动态获取配置文件，当缓存配置信息超过5分钟后重新缓存
	private static String getDynamicProperty(String key,String resourceName){
		long currentTime = System.currentTimeMillis();
		if(null==preLoadTime.get(StringUtils.upperCase(resourceName)) || 
		   DYNAMIC_LOAD_TIME <= (currentTime-preLoadTime.get(StringUtils.upperCase(resourceName)).longValue()) ){
			MarvelsLogUtil.getInstance().info("PropertyLoadUtils reload pss.properties begin");
				
				loadPropertiesCache(resourceName);
				
				MarvelsLogUtil.getInstance().info("PropertyLoadUtils reload pss.properties end");
		}
		return StringUtils.trim(cacheProperties.get(StringUtils.upperCase(resourceName)).getProperty(key));
	}
	
	//加载配置文件，并缓存
	private static void loadPropertiesCache(String resourceName){
			Properties prop = loadProperties(resourceName);
			cacheProperties.put(StringUtils.upperCase(resourceName), prop);
			preLoadTime.put(StringUtils.upperCase(resourceName), Long.valueOf(System.currentTimeMillis()));
    }
	
	//加载配置文件
	private static Properties loadProperties(String resourceName){
			try {
					//获取当前ClassPath的绝对URI路径
				    ClassLoader classLoaderToUse = Thread.currentThread().getContextClassLoader();;
				    if (classLoaderToUse == null) {
				      classLoaderToUse =PropertiesLoadUtil.class.getClassLoader();
				    }

				    Enumeration<URL> urls = classLoaderToUse != null ? classLoaderToUse.getResources(resourceName) : 
				      ClassLoader.getSystemResources(resourceName);
				    
				    //读取配置文件内容
				    Properties props = new Properties();
				    while (urls.hasMoreElements()) {
				      URL url = (URL)urls.nextElement();
				      URLConnection con = url.openConnection();
				      InputStream is = con.getInputStream();
                      try{
                    	  props.load(is);
                      }finally{
                    	  is.close();
                      }
				    }
				    return props;
			} catch (IOException e) {
				MarvelsLogUtil.getInstance().error("load propertis "+resourceName+" is error",e);
				return new Properties();
			}
	}
}
